<template>
  <div class="container-content">
    <div>
      <el-form
        :inline="true"
        ref="ruleFormRef"
        :model="formInline"
        class="demo-form-inline"
      >
        <el-form-item prop="isInclude">
          <el-switch
            v-model="formInline.isInclude"
            class="ml-2"
            inline-prompt
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            active-text="包含下级"
            inactive-text="不包含下级"
          />
        </el-form-item>
        <el-form-item prop="deptId">
          <el-tree-select
            v-model="formInline.deptId"
            :data="deptOptions"
            :props="{ label: 'label', children: 'children' }"
            :render-after-expand="false"
            node-key="id"
            :check-strictly="true"
            :check-on-click-node="true"
            :expand-on-click-node="false"
            placeholder="请选择行政区"
          />
        </el-form-item>
        <el-form-item prop="areatypeId">
          <el-select
            v-model="formInline.areatypeId"
            placeholder="行政区划类型"
            clearable
          >
            <el-option label="地市" value="1" />
            <el-option label="区县" value="2" />
            <el-option label="镇街" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item prop="gridtypeno">
          <el-select
            v-model="formInline.gridtypeno"
            placeholder="电子围栏类型"
            clearable
          >
            <el-option label="地市电子围栏" value="01" />
            <el-option label="区县电子围栏" value="02" />
            <el-option label="镇街电子围栏" value="03" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="handleReset(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="width: 100%; height: calc(100% - 55px); position: relative">
      <div id="container" v-loading="loading" class="container"></div>
      <div style="position: absolute; top: 10px; left: 10px" id="myPageTop">
        <table>
          <tr>
            <td>
              <label style="font-size: 12px">请输入关键字：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input style="height: 26px" id="tipinput" />
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script src=""></script>
<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import { onMounted, reactive, ref } from "vue";
import { getGridInfoList } from "@/api/map/index";

import { deptTreeSelect } from "@/api/system/user";

const ruleFormRef = ref();
const formInline = reactive({
  areatypeId: "",
  deptId: "",
  gridtypeno: "",

  isInclude: false,
});
const loading = ref(false);
const polygonList = ref([]);
const textList = ref([]);
const onSubmit = () => {
  console.log(formInline);
  getGridInfoListData();
};

const handleReset = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  getGridInfoListData();
};
const state = reactive({
  center: [106.56901, 29.55566], // 地图中心点
  point: [106.56901, 29.55566], // 经纬度-lng lat
  map: null, // 地图实例
  marker: null, // 地图icon
  geocoder: null, // 逆解析实例
  address: "", // 地址
  weatherCity: "重庆",
  weather: null,
  data: [],
  style: {},
});

const deptOptions = ref(undefined);
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}

onMounted(() => {
  initMap().then((res) => {
    getGridInfoListData();
    getDeptTree();
  });
});
//获取行政区域地图电子围栏
const getGridInfoListData = () => {
  loading.value = true;
  getGridInfoList(formInline).then((res) => {
    loading.value = false;

    state.map.remove(polygonList.value);
    state.map.remove(textList.value);

    if (res.data.length === 0) {
      return;
    }

    polygonList.value = [];
    textList.value = [];
    res.data.forEach((item) => {
      let polygonItem = addPolygon(item.geometry.coordinates, item.gridStyle);
      polygonList.value.push(polygonItem);

      let textItem = addText(item.gridName, item.center.coordinates);
      textList.value.push(textItem);
    });
    if (polygonList.value.length !== 0 && textList.value.length !== 0) {
      state.map.add(polygonList.value);
      state.map.add(textList.value);
    }
  });
};
/**
 * DOM初始化完成进行地图初始化
 */
const initMap = () => {
  return new Promise((resolve) => {
    AMapLoader.load({
      key: "daf47c0ee853a30ffa8260c6491a1b0a", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      // 需要使用的的插件列表
      plugins: [
        "AMap.Geocoder", // 逆向地理解码插件
        "AMap.Marker", // 点标记插件
      ],
    })
      .then((AMap) => {
        console.log(state.center);
        state.map = new AMap.Map("container", {
          viewMode: "3D", // 地图视图模式，默认为‘2D’，可选’3D’，选择‘3D’会显示 3D 地图效果。
          zoom: 12, // 地图显示的缩放级别
          center: state.center, // 初始化地图中心点位置
        });
        // 如果父组件传入了有效值 回显一个icon
        if (state.point.length > 0) {
          // addMarker(AMap);
        }

        // state.map.on("click", (e) => {
        //   state.point = [e.lnglat.lng, e.lnglat.lat];
        //   console.log(AMap);
        //   addMarker(AMap);
        //   // 获取地址
        // });
        getSearch(AMap);

        resolve();
      })
      .catch((e) => {
        // message.error(e);
      });
  });
};
//地图搜索
const getSearch = (AMap) => {
  var autoOptions = {
    input: "tipinput",
  };
  AMap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], function () {
    var auto = new AMap.AutoComplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
      map: state.map,
    }); //构造地点查询类
    auto.on("select", select); //注册监听，当选中某条记录时会触发
    function select(e) {
      placeSearch.setCity(e.poi.adcode);
      placeSearch.search(e.poi.name); //关键字查询查询
    }
  });
};

const addText = (name, center) => {
  const text = new AMap.Text({
    text: name,
    anchor: "center", // 设置文本标记锚点
    draggable: false,
    cursor: "pointer",
    angle: 10,
    style: {
      "margin-bottom": "1rem",
      "border-radius": ".25rem",
      "background-color": "rgba(0,0,0,0)",
      width: "5rem",
      "border-width": 0,
      "text-align": "center",
      "font-size": "13.0px",
      "font-weight": "600",
      color: "#000",
    },
    position: center,
  });
  return text;
};
/**
 * 增加点标记
 * @param AMap AMap
 */
const addMarker = (AMap) => {
  // 清除其他icon
  if (state.marker) {
    state.marker.setMap(null);
    state.marker = null;
  }
  // 重新渲染icon
  state.marker = new AMap.Marker({
    icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
    size: new AMap.Size(53, 68), // 图标大小
    imageSize: new AMap.Size(53, 68),
    position: state.point, // icon经纬度
    offset: new AMap.Pixel(-28, -60), // icon中心点的偏移量
  });
  state.marker.setMap(state.map); // 设置icon
};

/**
 * 将经纬度转换为地址
 * @param AMap AMap
 */
const addPolygon = (data, style) => {
  const polygon = new AMap.Polygon({
    path: data,
    fillColor: style.gridFillcolor,
    strokeOpacity: 1,
    fillOpacity: 0.3,
    strokeColor: style.gridStrokecolor,
    strokeWeight: 1,
    cursor: "pointer",
    bubble: true,
    // strokeStyle: "dashed",
    strokeDasharray: [5, 5],
  });
  polygon.on("mouseover", () => {
    polygon.setOptions({
      fillOpacity: 0.7,
      fillColor: style.gridFillcolor,
    });
  });
  polygon.on("mouseout", () => {
    polygon.setOptions({
      fillOpacity: 0.3,
      fillColor: style.gridFillcolor,
    });
  });
  return polygon;
};
const getAddress = (AMap) => {
  // 这里通过高德 SDK 完成。
  state.geocoder = new AMap.Geocoder({
    city: "全国", // 地理编码时，设置地址描述所在城市; 默认全国; 可选值：城市名（中文或中文全拼）、citycode、adcode
    radius: 3000, // 逆地理编码时，以给定坐标为中心点; 默认1000; 取值范围(0-3000)
    extensions: "all", // 逆地理编码时，返回信息的详略; 默认值：base，返回基本地址信息; 默认值：base，返回基本地址信息
  });
  // 调用逆解析方法 个人开发者调用量上限5000（次/日）
  state.geocoder.getAddress(state.point, function (status, result) {
    if (status === "complete" && result.regeocode) {
      state.address = result.regeocode.formattedAddress;
      AMap.plugin("AMap.Weather", function () {
        if (
          result.info === "OK" &&
          result.regeocode.addressComponent.district
        ) {
          state.weatherCity = result.regeocode.addressComponent.district;
          // 获取天气
          getWeather(AMap);
        } else {
          // message.error("根据地址查询天气失败，请重新选择！");
        }
      });
    } else {
      // message.error("根据地址查询位置失败，请重新选择！");
    }
  });
};

/**
 * 获取天气
 * @param AMap AMap
 */
const getWeather = (AMap) => {
  AMap.plugin("AMap.Weather", function () {
    const weather = new AMap.Weather();
    // 执行实时天气信息查询
    weather.getLive(state.weatherCity, function (err, data) {
      if (data) {
        state.weather = data;
      } else {
        message.error(err);
      }
    });
  });
};

onUnmounted(() => {
  state.map?.destroy();
});
</script>

<style lang="scss" scoped>
.container-content {
  width: 100%;
  height: calc(100vh - 85px);

  padding: 10px 20px;
}
.container {
  position: relative;
  width: 100%;
  height: calc(100%);
  border: 1px solid #ececec;
  margin-top: 10px;
}
.toolbar {
  position: absolute;
  right: 10px;
  bottom: 10px;
  z-index: 99;
  max-width: 500px;
  .toolbar-item {
    display: flex;
    margin-bottom: 15px;
  }
}
.weather {
  position: absolute;
  right: 10px;
  bottom: 210px;
  z-index: 99;
}
</style>
